//
//  MicroAppCell.swift
//  TinyUI
//
//  Created by 徐涛 on 2020/3/25.
//  Copyright © 2020 葛晓良. All rights reserved.
//

import UIKit
import TinyUI
enum MicroAppCellType{
    case myApp  //我的APP
    case classification  //各种分组
    
}


class MicroAppCell: UICollectionViewCell ,MicroAnimToolDelegate{
    var titleLabel:UILabel=UILabel.init()//title
    let imgIcon:UIImageView=UIImageView.init()
    let imgWidth=37.0
    let imgHeight=37.0
    let img_lbl:CGFloat=15.0
    let titleHeight=20
    let angleaMarkViewHeight:CGFloat = 16
    let angleaMarkView:UIImageView=UIImageView.init()
    var iconUrl = String()
    var animS:CAKeyframeAnimation?
    var isHaveAdd = false//只在编辑状态下才有作用
    
    let redPointViewViewHeight:CGFloat = 10
    let redPointView:UIImageView=UIImageView.init(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
    
    let carryView:UIView=UIView.init()
    
    var request: AnyObject?
    
    
    let anim:MicroAnimTool=MicroAnimTool.init() //抛物动画
    let animTime:CGFloat=0.2
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initView()
        anim.toolDelegate=self
        anim.animTime=animTime
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    required init!(element: Element!) {
        fatalError("init(element:) has not been implemented")
    }
    
    func initView(){
        self.backgroundColor=UIColor.clear
        carryView.backgroundColor=UIColor.clear;
        self.addSubview(carryView)
        
        
        if imgIcon.superview == nil {
            imgIcon.frame=CGRect(x: 0, y: 0, width: 40, height: 40)
            imgIcon.backgroundColor=UIColor.clear
            imgIcon.center=CGPoint(x: self.bounds.size.width/2.0, y: self.bounds.size.height/2.0-10)
            self.carryView.addSubview(imgIcon)
        }
        if titleLabel.superview==nil {
            titleLabel = UILabel(frame: CGRect(x: 0, y: Int(imgIcon.frame.origin.y+imgIcon.frame.size.height+img_lbl),width:Int(Float(carryView.bounds.size.width)), height: titleHeight))
            titleLabel.textAlignment = NSTextAlignment.center
            titleLabel.font=UIFont.systemFont(ofSize: 13)
            titleLabel.adjustsFontSizeToFitWidth=true
            titleLabel.textColor=UIColor.tyColor(withHex: "#000000");
            self.carryView.addSubview(titleLabel)
        }
        
        if angleaMarkView.superview==nil {
            let originX=self.bounds.width-6-angleaMarkViewHeight
            angleaMarkView.frame=CGRect(x: originX, y: 6, width: angleaMarkViewHeight, height: angleaMarkViewHeight)
            angleaMarkView.layer.zPosition=100;
            self .addSubview(angleaMarkView)
        }
        if redPointView.superview==nil {
            let originX=self.bounds.width-6-redPointViewViewHeight
            redPointView.frame=CGRect(x: originX, y: 6, width: redPointViewViewHeight, height: redPointViewViewHeight)
            redPointView.layer.zPosition=100;
            self .addSubview(redPointView)
            redPointView.isHidden=true
        }
    }
    
    
    func configWithParams(model:MicroAppModels , state:TCMicroAppStoreState, isMyApp:ObjCBool ,myApps:NSMutableArray? = nil,dependence:NSDictionary? = nil)  {
        
        
        //******frame*********
        var iconHeight:CGFloat=26
        var iconWidth:CGFloat=26
        var aSide:CGFloat = 10
        
        if let k:String = dependence?["icon_height"] as? String {
            iconHeight=CGFloat(Double(k) ?? 0)
        }
        if let w = dependence?["icon_width"] as? String {
            iconWidth=CGFloat(Double(w) ?? 0)
        }
        if let color:String = dependence?["item-text-color"] as? String {
            titleLabel.textColor=UIColor.tyColor(withHex: color);
        }
        carryView.frame=CGRect(x: 0, y: 0, width:self.bounds.width, height:iconHeight+aSide+titleLabel.bounds.height)
        carryView.center=CGPoint(x: self.bounds.width/2.0, y: self.bounds.height/2.0)
        imgIcon.frame=CGRect(x: 0, y: 0, width: iconWidth, height: iconHeight)
        imgIcon.center=CGPoint(x: carryView.bounds.width/2.0, y: imgIcon.center.y)
        
        titleLabel.frame=CGRect(x: 0, y:carryView.bounds.height-titleLabel.bounds.height, width: carryView.bounds.width, height: CGFloat(titleHeight))
        
        
        self.angleaMarkView.isHidden=false
        self.imgIcon.image = UIImage(named:"MicroAppStore.bundle/defalut")
        self.imgIcon.contentMode=UIView.ContentMode.scaleAspectFit
        if model.icon != nil{
            //            if self.iconUrl != model.icon{
            self.iconUrl = model.icon!
            self.loadImageWith(urlStr: self.iconUrl)
            //            }
        }
        
        
        titleLabel.text=model.appName
        //        self.layer.borderWidth=1
        self.angleaMarkView.layer.masksToBounds=true;
        self.angleaMarkView.layer.cornerRadius=0;
        self.angleaMarkView.backgroundColor=UIColor.clear;
        self.redPointView.isHidden=true
        if state == TCMicroAppStoreState.nomal {
            self.angleaMarkView.isHidden=true
            if (model.isNeedNewMark) || (model.hasWidget == "1") {
                
                self.redPointView.isHidden=true;//去掉小红/绿点改为true
                if(model.hasWidget == "1"){
                    self.redPointView.backgroundColor=UIColor.clear;
                    self.redPointView.image = UIImage(named:"MicroAppStore.bundle/hasWidget");
                }
                if (model.isNeedNewMark) {
                    self.redPointView.image=nil;
                    self.redPointView.backgroundColor=UIColor.red;
                }
                self.redPointView.layer.masksToBounds=true;
                self.redPointView.layer.cornerRadius=redPointViewViewHeight/2.0;
            }
            self.layer.borderColor=UIColor.clear.cgColor
        }else if state == TCMicroAppStoreState.show {
            if (model.isNeedNewMark) || (model.hasWidget == "1"){
                self.redPointView.isHidden=true;//去掉小红/绿点改为true
                if(model.hasWidget == "1"){
                    self.redPointView.backgroundColor=UIColor.clear;
                    self.redPointView.image = UIImage(named:"MicroAppStore.bundle/hasWidget");
                }
                if (model.isNeedNewMark) {
                    self.redPointView.image=nil;
                    self.redPointView.backgroundColor=UIColor.red;
                }
                self.redPointView.layer.masksToBounds=true;
                self.redPointView.layer.cornerRadius=redPointViewViewHeight/2.0;
            }
            self.angleaMarkView.isHidden=true
        }else {
            if isMyApp.boolValue{//我的App用y减号
                self.angleaMarkView.image=UIImage(named:"MicroAppStore.bundle/edit_delete")
            }else{//用加号
                //                model.isInMy = isInMyAPP(model: model,myApps: myApps )
                if !model.isInMy {
                    self.angleaMarkView.image=UIImage(named:"MicroAppStore.bundle/edit_add")
                }else{
                    self.angleaMarkView.isHidden=true
                }
            }
        }
    }
    
    public func imageShake(){
//        let stand = ((20) / 180.0 * M_PI)
//        if animS == nil {
//            animS = CAKeyframeAnimation(keyPath: "transform.rotation")
//            animS!.values = [-stand , stand ];
//            animS!.duration = 0.1;
//            animS!.repeatCount = 2.5;
//
//            animS!.isRemovedOnCompletion = true;
//            animS!.fillMode = CAMediaTimingFillMode.forwards;
//        }
//        self.imgIcon.layer.add(animS!, forKey: nil)
        
        let frame = self.imgIcon.frame
        imgIcon.frame = CGRect(x: frame.midX, y: frame.maxY, width: 0, height: 0)
        UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0, options: .curveLinear, animations: {
            self.imgIcon.frame = frame
        }, completion: nil);
    }
    
    func isInMyAPP(model:MicroAppModels,myApps:NSMutableArray? = nil) -> Bool {
        let idSer = NSPredicate(format: "appKey=%@", model.appKey ?? "")
        if (myApps != nil){
            if let arr:Array = myApps?.filtered(using: idSer) {
                return arr.count > 0
            }
        }
        return false
    }
    
    func configCollapse(dependence:NSDictionary? = nil,dependencePath:String)  {
        let iconHeight:CGFloat=30
        let iconWidth:CGFloat=30
        let aSide:CGFloat = 10
        
        carryView.frame=CGRect(x: 0, y: 0, width:self.bounds.width, height:iconHeight+aSide+titleLabel.bounds.height)
        carryView.center=CGPoint(x: self.bounds.width/2.0, y: self.bounds.height/2.0)
        imgIcon.frame=CGRect(x: 0, y: 0, width: iconWidth, height: iconHeight)
        imgIcon.center=CGPoint(x: carryView.bounds.width/2.0, y: imgIcon.center.y)
        
        titleLabel.frame=CGRect(x: 0, y:carryView.bounds.height-titleLabel.bounds.height, width: carryView.bounds.width, height: CGFloat(titleHeight))
        titleLabel.text="收起"
        if let color:String = dependence?["item-text-color"] as? String {
            titleLabel.textColor=UIColor.tyColor(withHex: color);
        }
        self.angleaMarkView.isHidden=true
        self.layer.borderColor=UIColor.tyColor(withHex: "#ccddcc")?.cgColor
        if let icon:String = dependence?["item-collapse-icon"] as? String {
            MicroDataStoreHelper.loadImageWithUrlPath(path: icon, dependencePath: dependencePath){[weak self] (image) in
                self?.imgIcon.contentMode=UIView.ContentMode.center
                self?.imgIcon.image=image
            }
        }else{
            imgIcon.contentMode=UIView.ContentMode.scaleAspectFit
            imgIcon.image=UIImage(named:"MicroAppStore.bundle/collapse")
        }
    }
    
    func loadImageWith(urlStr:String)  {
        if !urlStr.isEmpty {
            guard let networkHelper: TinyUINetworkProtocol = TinyService.sharedInstance()?.instance(with: NSProtocolFromString("TinyUINetworkProtocol")!) as? TinyUINetworkProtocol else {
                return;
            }
            self.request =    networkHelper.imageRequest(withUri: urlStr, relativeUrl: nil, option: nil, completion: { [weak self] (data: Data?, error: Error?) in
                guard let r_data = data else {
                    self?.imgIcon.image = UIImage(named:"MicroAppStore.bundle/defalut")
                    return;
                }
                self?.imgIcon.image = UIImage.init(data: r_data)
            }) as AnyObject?
        }
    }
    
    //MARK:-toolDele
    func animationIsDidStop(isStop: Bool) {
        if isStop {
            self.anim.animLayer?.removeFromSuperlayer()
            self.anim.animLayer=nil
        }
    }
}
